#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <strings.h>
#include <sys/time.h>
#include <string.h>

int main(int argc,char *argv[]){

    // 参数
    if(argc < 2){
        fprintf(stderr,"Usage argc ... \n");
        exit(-1);
    }  


    // 监听文件描述符
    int lfd = socket(PF_INET,SOCK_STREAM,0);
    if(lfd < 0){
        fprintf(stderr,"socket error\n");
        exit(-1);
    }  

    // 绑定端口号
    struct sockaddr_in ser_addr;
    bzero(&ser_addr,sizeof(ser_addr));
    ser_addr.sin_family = AF_INET;
    ser_addr.sin_port = htons(atoi(argv[1]));
    ser_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    if(bind(lfd,(struct sockaddr *)&ser_addr,sizeof(ser_addr)) < 0){
        fprintf(stderr,"bind error\n");
        exit(-1);
    }

    // 监听
    if(listen(lfd,5) < 0){
        fprintf(stderr,"bind error\n");
        exit(-1);
    }  

    struct sockaddr_in cli_addr;
    socklen_t cli_len = sizeof(cli_addr);
    bzero(&cli_addr,cli_len);
    char buf[1024];
    int n;
    int cfd;


    // IO复用
    fd_set reads,temp;
    // 初始化
    FD_ZERO(&reads);
    // 将监听文件描述符加入
    FD_SET(lfd,&reads);
    int maxfd = lfd;
    int nready;
    while (1){
        temp = reads;
        nready = select(maxfd + 1,&temp,NULL,NULL,NULL);
        if(nready < 0){
            fprintf(stderr,"select error!\n");
            exit(-1);
        }else if(nready == 0){
            continue;
        }

        // 先判断是否有连接请求
        if(FD_ISSET(lfd,&temp)){
            int cfd = accept(lfd,(struct sockaddr *)&cli_addr,&cli_len);
            printf("clinet is ip=[%s] port=[%d]\n",inet_ntoa(cli_addr.sin_addr),ntohs(cli_addr.sin_port));
            // 将cfd加入
            FD_SET(cfd,&reads);
            if(maxfd < cfd){
                maxfd = cfd;
            }  
            if(!(--nready)){
                continue;
            }
        }  

        // 数据
        for (size_t i = lfd + 1; i < maxfd  + 1; i++){
            if(FD_ISSET(i,&temp)){
                memset(buf,'\0',sizeof(buf));
                n = read(i,buf,sizeof(buf));
                if(n == 0){
                    FD_CLR(i,&reads);
                    close(i);
                    printf("client %ld is closed\n",i);
                }else{
                    write(i,buf,n);
                }
                if(--nready == 0){
                    break;
                }
            }  
        }
         

    }

    close(lfd);
    return 0;
}